import { useEffect, useState } from 'react'
import Taro, { FC, UserInfo } from '@tarojs/taro'
import { Subject, Subscription } from 'rxjs';
import { debounceTime, filter, switchMap, tap } from 'rxjs/operators';
import { AtList, AtListItem, AtInput } from "taro-ui"
import { View, Text, Picker } from '@tarojs/components'
import TaroCropper from 'taro-cropper-v3';
import "taro-ui/dist/style/components/input.scss";
import "taro-ui/dist/style/components/button.scss" // 按需引入 
import { uploadFile } from "@/utils/qcloudHelpers";
import { useAuthFacade } from '@/hooks/useAuthFacade';
import { onEmit } from '@/utils/rxHelpers';
import { getLogger } from '@/utils/log';
import { APPROVE_STATUS } from '@/constants/user';
import { useMsgFacade } from '@/hooks/useMsgFacade';

import './index.scss'

//个人信息编辑 
export const EditInfo: FC = () => {
  const logger = getLogger("/pages/my/editInfo");
  //用不到的变量不用写
  const [authFacade, , , realName, orgs, userInfo, userApproveStatus, orgApproveStatus, , , desc, sexual] = useAuthFacade();
  const [msgFacade] = useMsgFacade();

  const initSubject = () => new Subject<any>();
  const [emitter, setEmitter] = useState<Subject<any>>(initSubject)

  const [nickname, setNickname] = useState(''); //用户昵称
  const [currentSex, setcurrentSex] = useState(0); //用户性别
  const [describe, setDescribe] = useState(''); //个人简介
  const [src, setSrc] = useState("");
  // const [avatar, setAvatar] = useState('https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/tx.png');
  const [avatar, setAvatar] = useState(ASSETS_PATH + '/default_avator.png');
  const [taroCropper, setTaroCropper] = useState(new TaroCropper(null))
  const [show, setShow] = useState(0)

  //把按钮点击事件转化为observable
  const userUpdate$ = emitter.asObservable()
    .pipe(
      //防抖动(防重复)
      debounceTime(400),
      //接收按钮点击的参数
      switchMap((userUpdateObj) => {
        console.log("userUpdateObj: ", userUpdateObj);
        if (!userUpdateObj.avatar) {
          throw Taro.showToast({
            title: '请上传头像',
            icon: 'none',
            duration: 2000
          })
        }
        if (!userUpdateObj.nickname) {
          throw Taro.showToast({
            title: '请输入昵称',
            icon: 'none',
            duration: 2000
          })
        }
        if (userUpdateObj.sexual === -1) {
          throw Taro.showToast({
            title: '请选择性别',
            icon: 'none',
            duration: 2000
          })
        }
        //昵称校验·
        // rsgName(userUpdateObj.nickname)
        if (userUpdateObj.nickname.length > 8) {
          throw Taro.showToast({
            title: '输入的昵称不能大于8个字数',
            icon: 'none',
            duration: 2000
          })
        }
        return authFacade.userUpdate(userUpdateObj)
          .pipe(
            tap(() => msgFacade.updateMyProfile(userUpdateObj.nickname, userUpdateObj.avatar))
          )
      })
    )

  // 性别选择
  const sexSelector = [
    {
      label: '女',
      value: 0
    }, {
      label: '男',
      value: 1
    }
  ]
  const catTaroCropper = (node: TaroCropper) => {
    setTaroCropper(node);
  }
  // 昵称
  const handleChange = (value: string) => {
    setNickname(value)
  }

  // 性别
  const handleChangeSex = (e) => {
    // setSex(value)
    setcurrentSex(Number(e.detail.value))
  }

  // 个人简介
  const handleChangeDescribe = (value: string) => {
    setDescribe(value)
  }

  // 跳转个人认证
  const toUserVerify = () => {
    if (userApproveStatus === APPROVE_STATUS.NEVER || userApproveStatus === APPROVE_STATUS.FAIL) {
      Taro.navigateTo({
        // url: '/pages/my/userVerify/index'
        url: '/subPages/my/userVerify/index'
      })
    }
  }
  // 跳转单位认证
  const toOrgVerify = () => {
    if (orgApproveStatus === APPROVE_STATUS.NEVER || orgApproveStatus === APPROVE_STATUS.FAIL) {
      Taro.navigateTo({
        // url: '/pages/my/orgVerify/index'
        url: '/subPages/my/orgVerify/index'
      })
    }
  }

  const toCropper = () => {
    Taro.chooseImage({
      count: 1,
    })
      .then(res => {
        setSrc(res.tempFilePaths[0]);
        setShow(1)
      })
  }

  useEffect(() => {
    updateUserInfo(userInfo, desc, sexual)

  }, [userInfo, desc, sexual])

  const updateUserInfo = (userInfo: UserInfo, desc: string, sexual: number) => {
    setcurrentSex(sexual ?? 0) // 后端返回空则取0
    setDescribe(desc)
    setNickname(userInfo.nickName)
    setAvatar(userInfo.avatarUrl)
  }

  useEffect(() => {
    //注册并执行所有rxjs流
    const subscriptions: Subscription[] = [
      authFacade.loginStatus$
        .pipe(
          debounceTime(500),
          filter(status => status), //登录后才执行后续
          switchMap(authFacade.getMe)

        )
        .subscribe(
          res => console.info("返回结果", res, 'orgs[]', orgs),
          err => logger.ERROR("获取个人信息错误", err)
        )
    ]

    //页面销毁时也销毁所有订阅，防止内存泄漏
    return () => { subscriptions.map(sub => sub.unsubscribe()) };
  }, [])

  useEffect(() => {
    console.log("是否每次都运行？")
    //注册并执行所有rxjs流
    const subscriptions: Subscription[] = [
      onEmit<any>(
        userUpdate$,
        () => {
          Taro.showToast({
            title: '保存成功',
            icon: 'none',
            duration: 2000
          })
        },
        err => {
          logger.ERROR("保存信息失败！", err);
          setEmitter(initSubject)
        }
      ),
      // 获取认证状态
      authFacade.getapproveStatus()
        .subscribe()
    ]

    //页面销毁时也销毁所有订阅，防止内存泄漏
    return () => { subscriptions.map(sub => sub.unsubscribe()) };
  }, [emitter])

  return (
    <View className='index'>
      <View className='main'>
        {/* <AtList>
          <AtListItem title='个人信息' className='title' />
        </AtList> */}
        <AtList >
          <AtListItem title='头像' arrow='right' extraThumb={avatar == '' ? userInfo.avatarUrl : avatar} onClick={toCropper} ></AtListItem>
        </AtList>
        <AtInput
          maxlength={8}
          name='value1'
          title='昵称'
          type='text'
          placeholder=''
          value={nickname}
          onChange={handleChange.bind(this)}
          className='text'
        >
          {/* <AtIcon value='chevron-right' size='20' color='#666'></AtIcon> */}
        </AtInput>

        {/* 性别 */}
        {/* <AtInput
          maxlength={2}
          name='value2'
          title='性别'
          type='text'
          placeholder=''
          value={sex}
          onChange={handleChangeSex.bind(this)}
          className='text'
        >
          <AtIcon value='chevron-right' size='20' color='#666'></AtIcon>
        </AtInput> */}

        <Picker mode='selector' value={sexSelector[currentSex].value} range={sexSelector} rangeKey='label' onChange={handleChangeSex}>
          <AtList>
            <AtListItem
              title='性别'
              extraText={sexSelector[currentSex].label}
            />
            <Text className='at-icon at-icon-chevron-right item-icon' style='font-size: 20px; color: #666; position: absolute; right: 5px; top: 17px; '></Text>

          </AtList>
        </Picker>

        {/* 个人简介 */}
        <AtInput
          maxlength={16}
          name='value3'
          title='个人简介'
          type='text'
          placeholder=''
          value={describe}
          onChange={handleChangeDescribe.bind(this)}
          className='text'
        >
          {/* <AtIcon value='chevron-right' size='20' color='#666'></AtIcon> */}
        </AtInput>

        {/* 个人认证 */}
        <View className={userApproveStatus === APPROVE_STATUS.SUCCESS ? "list-item" : "list-item1"} onClick={toUserVerify} >
          <View className='list-text'>
            <Text className='item-left'>个人认证</Text>
            <Text className={(userApproveStatus === APPROVE_STATUS.NEVER || userApproveStatus === APPROVE_STATUS.FAIL) ? "item-right " : 'item-right certified'}>
              {userApproveStatus === APPROVE_STATUS.SUCCESS ? "已认证" : userApproveStatus === APPROVE_STATUS.PENDING ? '审核中' : '去认证'}
            </Text>
          </View>
          {/* <Text className='at-icon at-icon-chevron-right item-icon' style='font-size: 20px;  color: #666 ; margin-right: -3px;'></Text> */}
        </View>
        {/* 机构认证 */}
        {userApproveStatus === APPROVE_STATUS.SUCCESS && (
          <View>
            <View className='list-item1' onClick={toOrgVerify}>
              <View className='list-text'>
                <Text className='item-left'>所属机构</Text>
                <Text className={orgApproveStatus === APPROVE_STATUS.NEVER || orgApproveStatus === APPROVE_STATUS.FAIL ? "item-right " : 'item-right certified'}>
                  {orgApproveStatus === APPROVE_STATUS.SUCCESS ? "已认证" : orgApproveStatus === APPROVE_STATUS.PENDING ? '审核中' : '去认证'}
                </Text>
              </View>
              {/* <Text className='at-icon at-icon-chevron-right item-icon' style='font-size: 20px;  color: #666 ; '></Text> */}
            </View>
          </View>)}


        {/* 认证失败 */}
        {(userApproveStatus === APPROVE_STATUS.FAIL || orgApproveStatus === APPROVE_STATUS.FAIL) && (
          <View className='approve-tip'>
            <Text>认证失败，</Text>
            <Text className='jump-approve' onClick={userApproveStatus === APPROVE_STATUS.FAIL ? toUserVerify : toOrgVerify}>再次认证</Text>
          </View>
        )}


        {/* 逻辑需要优化，怎么告诉客户端图片已经上传成功？ */}
        <View className='bt' onClick={e => emitter.next({
          nickname: nickname,
          avatar,
          sexual: currentSex,
          desc: describe,
        })}
        >
          <Text>保存</Text>
        </View>
        <View className='img' style={{ display: show == 0 ? "none" : "block" }}>
          <TaroCropper
            height={1000} src={src}
            cropperWidth={400}
            cropperHeight={400}
            ref={catTaroCropper}
            fullScreen
            onCut={res => {
              uploadFile(res,
                (resUrl: string) => {
                  //Fixme， 上传完成之前，都不允许点击保存按钮，否则请求后端的图片参数为空
                  setAvatar(resUrl)
                },
              )
              setShow(0)
            }}
            hideCancelText={false}
            onCancel={() => {
              Taro.showToast({
                icon: 'none',
                title: '点击取消'
              })
              setShow(0)
            }}

          />
        </View>
      </View>
    </View >
  )
}
export default EditInfo